<template>
  <div class="home-container">
    <el-container class="home-layout">
      <!-- 侧边栏导航 -->
      <el-aside width="220px" class="home-sidebar">
        <div class="home-title">系统主页</div>
        <el-menu
          active-text-color="#409EFF"
          background-color="#f8f9fa"
          text-color="#333"
          @select="handleSelect"
          :default-openeds="['4']"
        >
          <el-menu-item index="1">
            <i class="el-icon-pie-chart"></i>
            <span>数据可视化界面</span>
          </el-menu-item>
          <el-menu-item index="2">
            <i class="el-icon-document"></i>
            <span>检修文件界面</span>
          </el-menu-item>
          <el-menu-item index="3">
            <i class="el-icon-notebook-2"></i>
            <span>台账管理界面</span>
          </el-menu-item>

          <!-- 模型展示界面 - 包含二级和三级菜单 -->
          <el-submenu index="4">
            <template slot="title">
              <i class="el-icon-cube"></i>
              <span>模型展示界面</span>
            </template>

            <!-- 全模型 - 二级菜单 -->
            <el-submenu index="4-1">
              <template slot="title">
                <span>全模型</span>
              </template>

              <!-- 全模型下的二级菜单项（后水悬吊管模型，无三级） -->
              <el-menu-item index="4-1-1">
                <span>后水悬吊管</span>
                <!-- 右侧展示组件的位置 -->
                <template #suffix>
                  <PostWaterSuspensionPipeModel
                    v-if="currentModelType === '后水悬吊管'"
                  />
                </template>
              </el-menu-item>

              <!-- 全模型下的二级菜单（全大屏模型，包含三级菜单） -->
              <el-submenu index="4-1-2">
                <template slot="title">
                  <span>全大屏模型</span>
                </template>

                <!-- 全大屏模型下的三级菜单项 -->
                <el-menu-item index="4-1-2-1">
                  <span>#1·全大屏</span>
                  <template #suffix>
                    <FullScreenModel1 v-if="currentModelType === '#1·全大屏'" />
                  </template>
                </el-menu-item>
                <el-menu-item index="4-1-2-2">
                  <span>#2·全大屏</span>
                  <template #suffix>
                    <FullScreenModel2 v-if="currentModelType === '#2·全大屏'" />
                  </template>
                </el-menu-item>
                <el-menu-item index="4-1-2-3">
                  <span>#3·全大屏</span>
                  <template #suffix>
                    <FullScreenModel3 v-if="currentModelType === '#3·全大屏'" />
                  </template>
                </el-menu-item>
                <el-menu-item index="4-1-2-4">
                  <span>#4·全大屏</span>
                  <template #suffix>
                    <FullScreenModel4 v-if="currentModelType === '#4·全大屏'" />
                  </template>
                </el-menu-item>
              </el-submenu>
            </el-submenu>
          </el-submenu>
        </el-menu>
      </el-aside>

      <!-- 主内容区 -->
      <el-container class="home-main">
        <el-header class="home-header">
          <div class="user-info">
            欢迎您，<span class="username">{{ userName }}</span>
            <el-button
              type="danger"
              size="small"
              icon="el-icon-switch-button"
              @click="handleLogout"
            >
              退出
            </el-button>
          </div>
        </el-header>

        <el-main class="home-content">
          <!-- 根据选择的菜单展示相应组件 -->
          <Ledgers v-if="ledgerManagement"></Ledgers>
          <component
            :is="currentComponent"
            v-if="currentComponent"
            :instanceId="instanceId"
            ref="activeModelComponent"
          />
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
// 导入所需组件
import Ledgers from "@/components/home/Ledgers.vue";
import HSX from "@/components/models/HSX.vue";

export default {
  name: "Home",
  components: {
    Ledgers,
    HSX,
  },
  data() {
    return {
      userName: localStorage.getItem("userName"),
      flags: this.initFlags(),
      currentModelType: "", // 用于存储当前选中的模型类型
      currentComponent: null, // 当前要显示的组件
      instanceId: null, // 实模ID
    };
  },
  computed: {
    // 计算属性用于判断是否显示台账管理组件
    ledgerManagement() {
      return this.flags.ledgerManagement;
    },
  },
  methods: {
    // 初始化所有标志为false
    initFlags() {
      return {
        dataVisualization: false,
        maintenanceFiles: false,
        ledgerManagement: false,
        modelDisplay: false,
      };
    },

    // 设置激活的菜单标志和当前组件
    setFlag(key) {
      // 第一步：先保存当前组件实例（关键：在重置状态前保存）
      const prevComponent = this.currentComponent;
      const prevComponentInstance = this.$refs.activeModelComponent;

      // 第二步：执行清理（使用保存的实例，避免被后续重置覆盖）
      this.cleanupPreviousComponent(prevComponent, prevComponentInstance);
      //  重置狀態
      this.flags = this.initFlags();
      this.currentComponent = null;
      this.currentModelType = "";
      this.instanceId = null; // 重置实模ID

      switch (key) {
        case "1":
          this.flags.dataVisualization = true;
          // 设置对应的数据可视化组件
          break;
        case "2":
          this.flags.maintenanceFiles = true;
          // 设置对应的检修文件组件
          break;
        case "3":
          this.flags.ledgerManagement = true;
          break;
        case "4-1-1":
          this.flags.modelDisplay = true;
          this.currentModelType = "后水悬吊管";
          this.currentComponent = "HSX";
          this.fetchInstanceId(this.currentModelType);
          break;
        case "4-1-2-1":
          this.flags.modelDisplay = true;
          this.currentModelType = "#1·全大屏";
          this.currentComponent = "FullScreenModel1";
          this.fetchInstanceId(this.currentModelType);
          break;
        case "4-1-2-2":
          this.flags.modelDisplay = true;
          this.currentModelType = "#2·全大屏";
          this.currentComponent = "FullScreenModel2";
          this.fetchInstanceId(this.currentModelType);
          break;
        case "4-1-2-3":
          this.flags.modelDisplay = true;
          this.currentModelType = "#3·全大屏";
          this.currentComponent = "FullScreenModel3";
          this.fetchInstanceId(this.currentModelType);
          break;
        case "4-1-2-4":
          this.flags.modelDisplay = true;
          this.currentModelType = "#4·全大屏";
          this.currentComponent = "FullScreenModel4";
          this.fetchInstanceId(this.currentModelType);
          break;
        default:
          break;
      }
    },

    // 清理上一个模型组件的资源
    cleanupPreviousComponent(prevComponent, prevInstance) {
      // 日志跟踪：确认方法是否进入
      console.log(
        "尝试清理上一个组件：",
        prevComponent,
        "实例：",
        prevInstance
      );

      // 条件判断：组件名存在且实例有效
      if (prevComponent && prevInstance) {
        // 检查实例是否有清理方法
        if (typeof prevInstance.cleanupThreeResources === "function") {
          console.log(`开始清理组件 ${prevComponent} 的资源`);
          prevInstance.cleanupThreeResources(); // 调用清理方法
        } else {
          console.warn(
            `组件 ${prevComponent} 未实现 cleanupThreeResources 方法`
          );
        }
      } else {
        console.log("无需要清理的组件实例");
      }
    },

    // 请求实模ID
    fetchInstanceId(instanceName) {
      this.loading = true;
      this.$api.modelInstanceModelsApi
        .queryId({ instanceName: instanceName })
        .then((res) => {
          this.loading = false;
          if (res.data.code === 1) {
            this.instanceId = res.data.data;
            // 将实模ID传递给子组件（HSX组件）
            if (this.currentComponent === "HSX") {
              // 可通过$refs通知子组件或依赖响应式更新
              console.log("实模ID获取成功:", this.instanceId);
            }
          } else {
            console.error("获取实模ID失败:", res.msg);
            this.$message.error(res.msg || "获取实模ID失败");
          }
        })
        .catch((error) => {
          this.loading = false;
          console.error("请求实模ID出错:", error);
          this.$message.error("网络异常，请检查网络连接");
        });
    },

    // 菜单选择事件处理
    handleSelect(key) {
      this.setFlag(key);
    },

    // 退出登录处理
    handleLogout() {
      this.$router.push({ name: "login" });
      this.$notify({
        title: "成功",
        message: "退出成功！",
        type: "success",
      });
    },
  },
  mounted() {
    // 默认显示数据可视化界面
    this.setFlag("1");
  },
};
</script>

<style scoped>
.home-container {
  height: 100vh;
  overflow: hidden;
  font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB",
    "Microsoft YaHei", Arial, sans-serif;
}

.home-layout {
  height: 100%;
}

.home-sidebar {
  background-color: #f8f9fa;
  border-right: 1px solid #e6e6e6;
  transition: width 0.3s;
}

.home-title {
  height: 60px;
  line-height: 60px;
  text-align: center;
  font-size: 18px;
  font-weight: bold;
  color: #333;
  border-bottom: 1px solid #e6e6e6;
  background-color: #f0f2f5;
}

.home-header {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  height: 60px;
  padding: 0 20px;
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.user-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.username {
  color: #606266;
  font-size: 14px;
}

.home-content {
  padding: 20px;
  background-color: #f5f7fa;
  height: calc(100% - 60px);
  overflow-y: auto;
}

/* 菜单项样式优化 */
.el-menu {
  border-right: none;
}

.el-menu-item,
.el-submenu__title {
  height: 50px;
  line-height: 50px;
  font-size: 14px;
  transition: all 0.2s;
}

.el-menu-item:hover,
.el-submenu__title:hover {
  background-color: #e6f7ff !important;
}

.el-menu-item.is-active {
  background-color: #e6f7ff !important;
  border-left: 3px solid #409eff;
}

/* 三级菜单缩进调整 */
.el-menu .el-menu .el-menu-item {
  padding-left: 45px !important;
}

/* 四级菜单缩进调整 */
.el-menu .el-menu .el-menu .el-menu-item {
  padding-left: 65px !important;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .home-sidebar {
    width: 64px !important;
  }
  .home-title,
  .el-menu-item span,
  .el-submenu__title span {
    display: none;
  }
  .el-menu-item,
  .el-submenu__title {
    text-align: center;
    padding: 0 !important;
  }
  .el-menu .el-menu .el-menu-item {
    padding: 0 !important;
  }
}

/* 组件过渡效果 */
.home-content > * {
  transition: all 0.3s ease-in-out;
}
</style>
